<template>
  <div class="search-bar">
    <div v-if="showWeather" class="weather-widget" @click="goToWeather">
      <WeatherWidget />
    </div>
    <div class="search-input">
      <van-search
        v-model="keyword"
        :placeholder="placeholder"
        shape="round"
        background="transparent"
        @search="onSearch"
        @focus="onFocus"
        @blur="onBlur"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { debounce } from '../../utils/common'
import WeatherWidget from './WeatherWidget.vue'

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索博客'
  },
  showWeather: {
    type: Boolean,
    default: true
  },
  hotKeywords: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['search', 'focus', 'blur'])

const router = useRouter()
const keyword = ref('')
const isFocused = ref(false)

// 搜索处理
const onSearch = () => {
  if (!keyword.value.trim()) return
  
  emit('search', keyword.value)
  router.push({
    path: '/blog',
    query: { q: keyword.value }
  })
}

// 防抖处理的搜索建议
const debouncedSearch = debounce((value) => {
  emit('search', value)
}, 300)

// 输入框获得焦点
const onFocus = () => {
  isFocused.value = true
  emit('focus')
}

// 输入框失去焦点
const onBlur = () => {
  isFocused.value = false
  emit('blur')
}

// 跳转到天气页面
const goToWeather = () => {
  router.push('/weather')
}
</script>

<style lang="scss" scoped>
.search-bar {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: var(--background-color-light);
  
  .weather-widget {
    margin-right: 8px;
    flex-shrink: 0;
  }
  
  .search-input {
    flex: 1;
    
    :deep(.van-search) {
      padding: 0;
    }
    
    :deep(.van-search__content) {
      background-color: var(--background-color);
    }
  }
}
</style> 